<template>
	<view class="wrap">
		<view class="key-input">
			<view class="title">输入验证码</view>
			<view class="tips">验证码已发送至 {{email}}</view>
			<u-message-input :focus="true" :value="value" @change="change" @finish="finish" mode="box" :maxlength="maxlength"></u-message-input>
			<text :class="{ error: error }">验证码错误，请重新输入</text>
			<view class="captcha">
				<text :class="{ noCaptcha: show }" @tap="noCaptcha">收不到验证码点这里</text>
				<text :class="{ regain: !show }">{{ second }}秒后重新获取验证码</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		sendMailCode,
		checkMailCode
	} from '../../api/common'
	export default {
		data() {
			return {
				email: '',
				type: 1,
				maxlength: 6,
				value: '',
				second: 60,
				show: false,
				error: false
			};
		},
		computed: {},
		onLoad(option) {
			this.email = option.email;
			this.type = option.type;
			this.sendCode(this.email, this.type)
		},
		methods: {
			//发送验证码
			sendCode(email, type) {
				return new Promise((resolve, reject) => {
					let interval = setInterval(() => {
						this.second--;
						if (this.second <= 0) {
							this.show = true;
							if (this.value.lenth != 6) {
								this.error = true;
							}
							clearInterval(interval);
						}
					}, 1000);
					sendMailCode({
						email,
						type
					}).then(res => {
						if (res.code == 200) {
							resolve('ok')
						} else {
							reject(res.msg)
						}
					}).catch(e => {
						reject(e.msg)
					})
				})
			},
			// 检查验证码
			checkCode(email, code, type) {
				return new Promise((resolve, reject) => {
					checkMailCode({
						email,
						code,
						type
					}).then(res => {
						if (res.code == 200) {
							resolve(res.data.token)
						} else {
							reject(res.msg)
						}
					}).catch(e => {
						reject(e.msg)
					})
				})
			},
			// 收不到验证码选择时的选择
			noCaptcha() {
				this.sendCode(this.email, this.type)
			},
			// change事件侦听
			change(value) {
				// console.log('change', value);
			},
			// 输入完验证码最后一位执行
			finish(value) {
				this.checkCode(this.email,value,3).then(res =>{
					uni.navigateTo({
						url:`/pages/user/reset?token=${res}&email=${this.email}&type=1`
					})
				}).catch(e =>{
					
				})
			}
		}
	};
</script>

<style lang="scss" scoped>
	.wrap {
		padding: 60rpx;
	}

	.box {
		margin: 30rpx 0;
		font-size: 30rpx;
		color: 555;
	}

	.key-input {
		padding: 30rpx 0;

		text {
			display: none;
		}

		.error {
			display: block;
			color: red;
			font-size: 30rpx;
			margin: 20rpx 0;
		}
	}

	.title {
		font-size: 50rpx;
		color: #333;
	}

	.key-input .tips {
		font-size: 30rpx;
		color: #333;
		margin-top: 20rpx;
		margin-bottom: 60rpx;
	}

	.captcha {
		color: $u-type-warning;
		font-size: 30rpx;
		margin-top: 40rpx;

		.noCaptcha {
			display: block;
		}

		.regain {
			display: block;
		}
	}
</style>
